<?php
declare(strict_types=1);

namespace Database;


use Database\Base\ActiveQueryInterface;
use Kiri\Abstracts\Component;
use Kiri\Di\Context;
use Swoole\Coroutine;

/**
 * Class Relation
 * @package Kiri\db
 */
class Relation extends Component
{

    /** @var ActiveQuery[] $_query */
    private array $_query = [];

    /**
     * @param string $identification
     * @param ActiveQuery $query
     * @return $this
     */
    public function bindIdentification(string $identification, ActiveQuery $query): static
    {
        $this->_query[$identification] = $query;
        return $this;
    }

    /**
     * @param string $identification
     * @return bool
     */
    public function hasIdentification(string $identification): bool
    {
        return isset($this->_query[$identification]);
    }

    /**
     * @param string $name
     * @return ActiveQuery|null
     */
    public function getQuery(string $name): ?ActiveQuery
    {
        return $this->_query[$name] ?? null;
    }


    /**
     * @param string $_identification
     * @return mixed
     * @throws
     */
    public function first(string $_identification): mixed
    {
        if (!Context::exists($_identification)) {
            Context::set($_identification, $this->_query[$_identification]->first());
        }
        return Context::get($_identification);
    }


    /**
     * @param string $_identification
     * @return mixed
     */
    public function count(string $_identification): mixed
    {
        if (!Context::exists($_identification)) {
            Context::set($_identification, $this->_query[$_identification]->count());
        }
        return Context::get($_identification);
    }


    /**
     * @param string $_identification
     * @return mixed
     * @throws
     */
    public function get(string $_identification): mixed
    {
        if (Context::exists($_identification)) {
            Context::set($_identification, $this->_query[$_identification]->get());
        }
        return Context::get($_identification);
    }

}
